package triDataStruct;

import triStorage.*;
import transaction.*;
import utils.Constants;

public class RemovableMap {

	private IReader reader;
	private IRandIntAccess access;
	private long pos;
	
	public RemovableMap(IReader reader, IRandIntAccess access) {
		this.reader = reader;
		this.access = access;
		this.pos = -1;
	}
	
	private String readNextKey() {
		Integer flag;
		while (true) {
			flag = reader.readInt();
			if (flag == null)
				return null;
			pos = reader.getReadPos();
			if (flag == 0) {
				reader.skipString();
				reader.readInt();
			}
			else
				break;
		}
		
		return reader.readString();
	}
	
	//time-consuming
	public void removeItem(String key, int value, Transaction tx) {
		String str;
		int v;
		while (true) {
			str = readNextKey();
			if (str == null)
				return;
			v = reader.readInt();
			if (str.equals(key) &&  v == value) {
				access.writeInt(pos - Constants.INT_SIZE, 0, tx);
				return;
			}
		}
	}
	
	public void removeItem(String key, Transaction tx) {
		String str;
		while (true) {
			str = readNextKey();
			if (str == null)
				return;
			if (str.equals(key)) {
				access.writeInt(pos - Constants.INT_SIZE, 0, tx);
				reader.readInt();
			}
		}
	}
	
	public void dispose() {
		access.dispose();
	}
	
}
